/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.service.cacheplugins  
 */
package com.apache.bid.service.cacheplugins;

import java.math.BigDecimal;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.bid.common.BidCommonUtil;
import com.apache.bid.common.Constant;
import com.apache.bid.common.TeaUtil;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.common.cache.BidDataBaseRunable;
import com.apache.bid.common.vo.BidItemCacheVo;
import com.apache.bid.entity.BidApply;
import com.apache.bid.entity.BidInfoBaojia;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.entity.BidItemVip;
import com.apache.cache.util.Validator;
import com.apache.tools.DateUtils;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  报价提交方法
 * @author Hou Dayu 创建时间：2016-3-28  
 * 
 */
public class BaojiaSavePluginImpl implements PluginConnector {

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.zbxsoft.api.manager.PluginConnector#execute(com.zbxsoft.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo param) throws Exception {
		ResultEntity entity = new ResultEntity();
		String objId = String.valueOf(param.getParams("syncObjId"));
		Constant.getInstance().setJingjiaMap(objId, objId);
		final String key = Constant.getInstance().getJingjiaMap(objId);
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		synchronized (key) {//加入同步锁
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
			String itemId = String.valueOf(param.getParams("itemId"));
			String userEname = String.valueOf(param.getParams("userEname"));
			String myPrice = String.valueOf(param.getParams("myPrice"));
			param.setParams("bidTime", bidTime);
			BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + itemId);
			BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheObjectByKey(cache.item_prefix + itemId);
			BidInfoBaojia bjVo = (BidInfoBaojia) cache.getCacheCloneByKey(cache.baojia_prefix + userEname + "_"
					+ price.getItemId());
			String applyKey = "";
			if (Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
				applyKey = BidCacheManager.apply_prefix + userEname + "_" + itemId;
			} else {
				applyKey = BidCacheManager.apply_prefix + userEname + "_" + itemVo.getSessionId();
			}
			BidApply apply = (BidApply) cache.getCacheObjectByKey(applyKey);
			String vipKey = BidCacheManager.item_vip_prefix + userEname + "_" + itemId;
			BidItemVip vip = (BidItemVip) cache.getCacheObjectByKey(vipKey);
			String status = BidCommonUtil.getInstance().getStatus(price, bidTime);
			String myPriceStr = TeaUtil.decryptByTea(myPrice);
			ResultMsg msg = BidCommonUtil.getInstance().getCheckItem(status, myPriceStr, userEname, itemVo, price);
			if (!ToolsUtil.isEmpty(msg)) {
				entity.setResult("false");
				entity.setEntity("F".equals(msg.getFlag()) ? "false" : "true");
				entity.setMessage(msg.getMsg());
				return entity;
			}
			if (null != bjVo) {
				if ("0".equals(Validator.getDefaultStr(itemVo.getAllowUpdateTimes(), "0"))) {//允许修改报价的次数（bidmode=3/4使用）（缺省=0不允许修改）
					entity.setResult("false");
					entity.setEntity("false");
					entity.setMessage("您已报过价，不能修改报价信息");
					return entity;
				}
				int ifUpdateTimes = Integer.parseInt(itemVo.getAllowUpdateTimes());
				int updateTimes = Integer.parseInt(Validator.getDefaultStr(bjVo.getUpdateTimes(), "0"));
				if (updateTimes > ifUpdateTimes) {
					entity.setResult("false");
					entity.setEntity("false");
					entity.setMessage("您已超过允许修改的次数，不能修改报价信息");
					return entity;
				}
			}
			String itemStatus = String.valueOf(param.getParams("itemStatus"));
			if (status.equals(itemStatus) && Constant.getInstance().getItemConfig("exercise").equals(status)) {//行权期
				return exerciseItem(param, price, itemVo, apply, vip, bjVo);
			}
			if (Constant.getInstance().getItemConfig("exercise").equals(status)) {
				entity.setResult("false");
				entity.setEntity("false");
				entity.setMessage("标的不在行权期");
				return entity;
			}
			boolean mark = exeBaojia(param, price, itemVo, apply, vip, bjVo);
			if (mark) {
				entity.setResult("true");
				entity.setEntity("true");
				entity.setMessage("报价成功");
			} else {
				entity.setResult("false");
				entity.setEntity("false");
				entity.setMessage("报价失败");
			}
		}
		return entity;
	}

	private boolean exeBaojia(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip, BidInfoBaojia bjVo) throws Exception {
		ResultEntity entity = new ResultEntity();
		String itemId = String.valueOf(param.getParams("itemId"));
		String userEname = String.valueOf(param.getParams("userEname"));
		String myPrice = String.valueOf(param.getParams("myPrice"));
		String bidTime = String.valueOf(param.getParams("bidTime"));
		//String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();

		String bidNum = String.valueOf(param.getParams("bidNum"));
		String userIp = String.valueOf(param.getParams("userIp"));
		boolean mark = false;
		String exeType = "save";
		if (null != bjVo) {//判断是否同一人报价
			int updateTimes = Integer.parseInt(Validator.getDefaultStr(bjVo.getUpdateTimes(), "0"));
			bjVo.setUpdateTimes(String.valueOf(updateTimes + 1));
			bjVo.setBidValue(myPrice);
			bjVo.setUserIp(userIp);
			BigDecimal myPrices = new BigDecimal(TeaUtil.decryptByTea(myPrice));
			////////////本次报价涨幅//////////
			bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(itemVo.getFirstValuePre()))));
			bjVo.setAmount(String.valueOf(myPrices.multiply(new BigDecimal(itemVo.getItemNum()))));
			bjVo.setBidTime(bidTime);
			mark = BidCacheFactory.getInstance().getCacheManager("baojia").updateCacheObject(bjVo);
			exeType = "update";
		} else {
			bjVo = new BidInfoBaojia();
			bjVo.setUpdateTimes("0");
			bjVo.setBidValue(myPrice);
			bjVo.setUserIp(userIp);
			BigDecimal myPrices = new BigDecimal(TeaUtil.decryptByTea(myPrice));
			////////////本次报价涨幅//////////
			bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(itemVo.getFirstValuePre()))));
			bjVo.setAmount(String.valueOf(myPrices.multiply(new BigDecimal(itemVo.getItemNum()))));
			bjVo.setBidTime(bidTime);
			if (Validator.isEmpty(vip))
				bjVo.setRightLevel("0");
			else
				bjVo.setRightLevel(vip.getVipLevel());
			bjVo.setUserName(userEname);
			bjVo.setUserId(apply.getUserId());
			bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(price.getFirstValue()))));
			bjVo.setBidId(Validator.generate());
			bjVo.setItemId(itemId);
			bjVo.setBidNum(bidNum);
			mark = BidCacheFactory.getInstance().getCacheManager("baojia").createCacheObject(bjVo);
		}
		ParamsVo<BidInfoBaojia> vo = new ParamsVo<BidInfoBaojia>();
		vo.setObj(bjVo);
		BidDataBaseRunable runable = new BidDataBaseRunable(vo, "bidInfoBaojiaManager", exeType);
		BidCacheFactory.getInstance().exeDatabase(runable);
		String myPriceStr = TeaUtil.decryptByTea(myPrice);
		String maxPrice = "0";
		if (Validator.isNotNull(price.getLastValue())) {
			maxPrice = TeaUtil.decryptByTea(price.getLastValue());
		}
		if ((Constant.BIDMODE_YCXASC.equals(itemVo.getBidMode()) && new BigDecimal(myPriceStr)
				.compareTo(new BigDecimal(maxPrice)) > 0)
				|| (Constant.BIDMODE_YCXDESC.equals(itemVo.getBidMode()) && new BigDecimal(myPriceStr)
						.compareTo(new BigDecimal(maxPrice)) < 0)) {
			ParamsVo<BidItemPrice> priceVo = new ParamsVo<BidItemPrice>();
			price.setLastValue(myPrice);
			String itemStatus = String.valueOf(param.getParams("itemStatus"));
			if (Constant.getInstance().getItemConfig("exercise").equals(itemStatus)) {
				price.setIfPrioFlag("T");
			}
			price.setUserId(apply.getUserId());
			price.setUserName(userEname);
			priceVo.setObj(price);
			BidCacheFactory.getInstance().getCacheManager("itemPrice").updateCacheObject(price);
			BidDataBaseRunable runable2 = new BidDataBaseRunable(priceVo, "bidItemPriceManager", "update");
			BidCacheFactory.getInstance().exeDatabase(runable2);
		}
		if (mark) {
			entity.setResult("true");
			entity.setEntity("true");
			entity.setMessage("报价成功");
		} else {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("报价失败");
		}
		return mark;
	}

	/**
	 * description:  行权期
	 * @throws Exception 
	 */
	private ResultEntity exerciseItem(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip, BidInfoBaojia bjVo) throws Exception {
		ResultEntity entity = new ResultEntity();
		if (!"e".equals(vip.getVipType())) {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("您无权行权");
			return entity;
		}
		boolean mark = exeBaojia(param, price, itemVo, apply, vip, bjVo);
		if (mark) {
			entity.setResult("true");
			entity.setEntity("true");
			entity.setMessage("行权成功");
		} else {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("行权失败");
		}
		return entity;
	}
}
